package main

import (
	"flag"
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"os"
	"os/signal"
	"syscall"
)

// MQTT连接参数
const (
	brokerAaa    = "tcp://ud-taxi.com:1883"
	brokerBbb    = "tcp://taxi-mqtt.jjtoyo.com:1883"
	mqttUsername = "njtoyo-taxi"
	mqttPassword = "njtoyo-taxi"
)

func main() {
	topic := flag.String("topic", "", "receive topic")
	flag.Parse()
	fmt.Println("topic:", *topic)
	// 创建MQTT客户端选项
	optsAaa := mqtt.NewClientOptions().
		AddBroker(brokerAaa).
		SetClientID("client_from_aaa").
		SetCleanSession(true).
		SetKeepAlive(60).
		SetAutoReconnect(true).
		SetUsername(mqttUsername).
		SetPassword(mqttPassword)
	optsBbb := mqtt.NewClientOptions().
		AddBroker(brokerBbb).
		SetClientID("client_send_bbb").
		SetCleanSession(true).
		SetKeepAlive(60).
		SetAutoReconnect(true).
		SetUsername(mqttUsername).
		SetPassword(mqttPassword)

	// 创建MQTT客户端实例
	clientAaa := mqtt.NewClient(optsAaa)
	clientBbb := mqtt.NewClient(optsBbb)

	// 连接到broker aaa
	if token := clientAaa.Connect(); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
	}
	fmt.Println("Connected to broker 测试服")

	// 连接到broker bbb
	if token := clientBbb.Connect(); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
	}
	fmt.Println("Connected to broker 正式服")

	// 定义消息回调函数
	messageHandler := func(client mqtt.Client, msg mqtt.Message) {
		fmt.Printf("Received message from 测试服'%s' on topic '%s'\n\n", msg.Payload(), msg.Topic())
		// 将消息转发到broker bbb
		fmt.Printf("Received message 转发 正式服 on topic '%s'\n\n", msg.Topic())
		token := clientBbb.Publish(*topic, 0, false, msg.Payload())
		token.Wait()
	}

	// 订阅topic
	if token := clientAaa.Subscribe(*topic, 0, messageHandler); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
	}

	// 处理信号以优雅地退出
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

	<-signalChan
	fmt.Println("Exiting...")
	clientAaa.Disconnect(250)
	clientBbb.Disconnect(250)
}
